import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Drawer,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import LocationDetails from './LocationDetails';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import AdButton from '@/components/AdButton';
import { codes, locationType } from './utils';
import AdSelect from '@/components/AdSelect';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ Location, common, loading }) => ({
  Location,
  loading: loading.effects['Location/LocationList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class LocationList extends Component {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    stepFormValues: {},
    visible: false,
    rechargeVisible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    isAbled: '',
    cardNo: '',
    cars: [],
    rowDetails: {},
    globalListData: [],
    tempList: [],
  };
  className = 'LocationList';

  columns = [
    {
      title: '区域名称',
      dataIndex: 'address',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
    },
    {
      title: '区域类型',
      dataIndex: 'type',
      render: (text, record) => <AdSelect onlyRead={true} value={text} data={locationType} />,
    },
    {
      title: '区域编码',
      dataIndex: 'adCode',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      width: 200,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      width: 150,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      // width: 150,
    },
  ];
  componentDidMount() {
    this.getLocationList();
  }

  onRef = ref => {
    this.child = ref;
  };

  getLocationList = (params = {}, type) => {
    const { dispatch } = this.props;
    const { globalListData } = this.state;
    const { id } = params;
    if (id) params.id = id;
    dispatch({
      type: 'Location/LocationList',
      payload: params,
      callback: res => {
        res.map(v => {
          if (v.childNumber > 0) v.children = [];
        });
        if (type == 'child') {
          this.locationData(res, globalListData, id);
          this.setState({ tempList: data });
        } else {
          if (res.length == 1) {
            this.getLocationList({ id: res[0].id }); //中国不展示
          } else {
            this.setState({
              globalListData: res,
            });
          }
        }
      },
    });
  };
  locationData = (dataChild, data, id) => {
    //1、判断返回有数据，就给一个空的children:[],
    //2、点击下一层加载数据时,判断返回有数据并且children为空时就将数据加进来；
    //3、判断加入哪条数据下？通过id
    data.forEach(v => {
      if (dataChild.length > 0 && v.id == id) {
        v.children = dataChild;
      } else if (v.children) {
        this.locationData(dataChild, v.children, id);
      }
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getLocationList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { ...value } = values;
    this.setState({
      formValues: value,
    });
    this.getLocationList(value);
  };

  //新建
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push(`/roadNetwork/locationList/locationAdd`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/roadNetwork/locationList/locationEdit/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.getLocationList(params);
  };

  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id, cardNo } = record;

    dispatch({
      type: 'Location/locationDetails',
      payload: { id },
      callback: res => {
        this.setState({
          isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
        });
      },
    });

    this.setState(
      {
        checkId: id,
        cardNo: cardNo,
        rowDetails: record,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      rechargeVisible: false,
    });
  };
  handleRechargeOK = () => {
    this.child.operatePaneButton();
  };
  getChildValue = data => {
    if (data == 'false') {
      this.handleCancel();
    }
  };
  //展开关闭：
  onExpandRow = (expanded, record) => {
    // console.log('expanded, record', expanded, record);
    expanded && this.getLocationList({ id: record.id }, 'child');
  };
  render() {
    const {
      loading,
      Location: { LocationList, locationDetails },
      form,
      isMobile,
      dictObject,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      selectedRows,
      updateModalVisible,
      stepFormValues,
      isAbled,
      checkId,
      cardNo,
      visible,
      rechargeVisible,
      rowDetails,
      expandForm,
      globalListData,
    } = this.state;
    // console.log('expandForm', expandForm);

    const selectDetails = locationDetails[checkId];
    const firstFormItem = (
      <FormItem label="区域名称">
        {getFieldDecorator('address')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="区域编码">
        {getFieldDecorator('adCode')(<Input placeholder="请输入" />)}
      </FormItem>
    );

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      selectedRows: selectedRows,
      code: codes.add,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '行政区域详情',
      code: codes.showDetail,
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <Button.Group>
            <AdButton onClick={this.handleEdit} type="primary" text="编辑" code={codes.edit} />
          </Button.Group>
        </span>
      ),
    };

    // console.log('===========', globalListData);
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          // data={LocationList}
          data={{ list: globalListData }}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          scrollX={1000}
          expandForm={expandForm}
          className={this.className}
          // pagination={false}
          onExpandRow={this.onExpandRow}
          disabledRowSelected={true}
        />
        <RightDraw {...rightDrawParams}>
          <LocationDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
      </Fragment>
    );
  }
}
